package com.hivekion.system.controller;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.hivekion.common.annotation.AutoLog;
import com.hivekion.common.entity.PagedResultVo;
import com.hivekion.common.entity.TreeNode;
import com.hivekion.common.enums.OperationTypeEnum;
import com.hivekion.common.exception.BusinessException;
import com.hivekion.system.domain.vo.*;
import com.hivekion.system.service.ISysUserService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.Set;

/**
 * 用户信息
 *
 * @author sutao
 */
@RestController
@RequestMapping("/system/user")
public class SysUserController {

      @Autowired
      private ISysUserService userService;

      @GetMapping("/list")
      public PagedResultVo<SysUserViewVo> list(SysUserSearchPageInputVo inputVo) {
	    PagedResultVo<SysUserViewVo> list = userService.selectUserList(inputVo);
	    return list;
      }

      @GetMapping("/getUserName")
      public String getUserName(String userIds) {
	    return userService.getUserName(userIds);
      }

      @PostMapping("/create")
      @PreAuthorize("@Permission.hasPermi('pro:sys:user:add')")
      @AutoLog(value = "新增用户", operationType = OperationTypeEnum.INSERT, module = "系统管理/用户管理")
      public boolean create(@RequestBody SysUserCreateInputVo inputDto) {
	    if (inputDto.getUserName() == null && inputDto.getPhoneNumber() == null) {
		  throw new BusinessException(500, "新增用户的用户名和密码都为空！");
	    }
	    if (inputDto.getUserName() == null && inputDto.getPhoneNumber() != null) {
		  inputDto.setUserName(inputDto.getPhoneNumber());
	    }
	    if (StringUtils.isBlank(inputDto.getUserName())) {
		  throw new BusinessException(500, "新增用户'" + inputDto.getUserName() + "'失败，登录账号不能为空");
	    }
	    if (!userService.checkUserNameUnique(inputDto.getUserName(), "")) {
		  throw new BusinessException(500, "新增用户'" + inputDto.getUserName() + "'失败，登录账号已存在");
	    }
	    if (!inputDto.getPhoneNumber().equals("")
		    && !userService.checkPhoneUnique(inputDto.getPhoneNumber(), "")) {
		  throw new BusinessException(500, "新增用户'" + inputDto.getUserName() + "'失败，手机号码已存在");
	    }

	    if (!inputDto.getEmail().equals("")
		    && !userService.checkEmailUnique(inputDto.getEmail(), "")) {
		  throw new BusinessException(500, "新增用户'" + inputDto.getUserName() + "'失败，邮箱账号已存在");
	    }
	    return userService.create(inputDto);
      }

      @PutMapping("/update")
      @AutoLog(value = "变更用户信息", operationType = OperationTypeEnum.UPDATE, module = "系统管理/用户管理")
      @PreAuthorize("@Permission.hasPermi('pro:sys:user:edit')")
      public boolean update(@RequestBody SysUserUpdateInputVo inputVo) {

	    SysUserModelVo info = userService.getInfo(inputVo.getId());

	    if (info != null
		    && !info.getUserName().equals(inputVo.getUserName())
		    && !userService.checkUserNameUnique(inputVo.getUserName(), inputVo.getId())) {
		  throw new BusinessException(500, "修改用户'" + inputVo.getUserName() + "'失败，登录账号已存在");
	    }
	    if (info != null
		    && info.getPhoneNumber() != null
		    && !info.getPhoneNumber().equals(inputVo.getPhoneNumber())
		    && StringUtils.isNotBlank(inputVo.getPhoneNumber())
		    && !userService.checkPhoneUnique(inputVo.getPhoneNumber(), inputVo.getId())) {
		  throw new BusinessException(500, "修改用户'" + inputVo.getUserName() + "'失败，手机号码已存在");
	    }
	    if (info != null
		    && info.getEmail() != null
		    && !info.getEmail().equals(inputVo.getEmail())
		    && !inputVo.getEmail().equals("")
		    && !userService.checkEmailUnique(inputVo.getEmail(), inputVo.getId())) {
		  throw new BusinessException(500, "修改用户'" + inputVo.getUserName() + "'失败，邮箱账号已存在");
	    }
	    return userService.update(inputVo);
      }

      @PostMapping("/checkUserNameUnique")
      public boolean checkUserNameUnique(String userName, String userId) {
	    if (!userService.checkUserNameUnique(userName, userId)) {
		  return true;
	    }
	    return false;
      }

      @PostMapping("/checkPhoneUnique")
      public boolean checkPhoneUnique(String phone, String userId) {
	    if (!userService.checkPhoneUnique(phone, userId)) {
		  return true;
	    }
	    return false;
      }

      @DeleteMapping("/delete")
      @PreAuthorize("@Permission.hasPermi('pro:sys:user:remove')")
      @AutoLog(value = "删除用户信息", operationType = OperationTypeEnum.DELETE, module = "系统管理/用户管理")
      public boolean delete(String userId) {
	    return userService.delete(userId);
      }

      @PostMapping("/resetPwd")
      @PreAuthorize("@Permission.hasPermi('pro:sys:user:resetPwd')")
      @AutoLog(value = "重置用户密码", operationType = OperationTypeEnum.UPDATE, module = "系统管理/用户管理")
      public boolean resetPwd(SysUserResetPwdVo pwdVo) {
	    return userService.resetPwd(pwdVo);
      }

      @PostMapping("/changeStatus")
      @PreAuthorize("@Permission.hasPermi('pro:sys:user:edit')")
      @AutoLog(value = "修改用户状态", operationType = OperationTypeEnum.UPDATE, module = "系统管理/用户管理")
      public boolean changeStatus(String userId, Integer status) {
	    return userService.changeStatus(userId, status);
      }

      @GetMapping("/getInfo")
      @AutoLog(value = "用户管理", operationType = OperationTypeEnum.SELECT, module = "系统管理/用户管理")
      public SysUserModelVo getInfo(String userId) {
	    return userService.getInfo(userId);
      }

      @GetMapping("/getUserTree")
      public List<TreeNode> getUserTree() {
	    return userService.getUserTree();
      }

      @ApiOperation(value = "根据区域查询统计员信息", notes = "根据区域查询统计员信息")
      @GetMapping("/getStatisticianByArea")
      public List<TreeNode> getStatisticianByArea(String areaCode) {
	    return userService.getStatisticianByArea(areaCode);
      }

      @ApiOperation(value = "查询用户管辖区域", notes = "查询用户管辖区域")
      @GetMapping("/getUserArea")
      public List<TreeNode> getUserArea(){
            return userService.getUserArea();
      }

	@ApiOperation(value = "删除重复用户", notes = "删除重复用户")
	@GetMapping("/delDuplicateUser")
	public boolean delDuplicateUser(){
		  userService.delDuplicateUser();
		  return true;
	}

	@ApiOperation(value = "更新用户区域绑定", notes = "更新用户区域绑定")
	@PostMapping("/updateFromExcel")
	public Set<String> updateFromExcel(MultipartFile excel) {
		  return userService.importExcel(excel);
	}

}
